<?php defined('SYSPATH') or die('No direct script access.');

	class Model_Services_MedicinePatient extends Model implements Jqgrid_GridListener{
		
		public $id_patient;
		public $medicine_patient = NULL;
		
		public function __construct($id=false){
			$this->id_patient = $id;
		}	
			
		public function count($criteria = false){
			return ORM::factory("dao_medicinepatient")->where("patient_id","=",$this->id_patient)->count_all();
		}
		
		public function getList($criteria = false){
				
			if (!$criteria)	$medicine_patient_list = ORM::factory("dao_medicinepatient")->where("patient_id","=",$this->id_patient)->find_all()->as_array();
			else $medicine_patient_list = ORM::factory("dao_medicinepatient")->where("patient_id","=",$this->id_patient)->order_by($criteria->sidx,$criteria->sord)->limit($criteria->limit)->offset($criteria->calcOffset())->find_all()->as_array();
		
			$dataset = array();
			foreach ($medicine_patient_list as $medicine_patient){
				$dataset[$medicine_patient->id] = array(	$medicine_patient->medicine->name,
															$medicine_patient->dosage,
															Helper_Service::factory("patient",$this->id_patient)->getAge() - $medicine_patient->age_at_start,
															$medicine_patient->patient_id);
			}
					
			return $dataset;
		}
				
		public function getCondition($orderfield, $ordertype, $start,$limit){
			return ORM::factory("dao_medicinepatient")->where("patient_id","=",$this->id_patient)->order_by($orderfield,$ordertype)->limit($limit)->find_all()->as_array();
		}
		
		
		public function get($id){
			return ORM::factory("dao_medicinepatient")->find($id);
		}
		
		
		public function save($id, array $data){
			$this->medicine_patient = ($id) ? ORM::factory("dao_medicinepatient",$id) : ORM::factory("dao_medicinepatient");
			
			//hacer funcion para pasar de string a numeros (una funcion sanitize input)
			$this->medicine_patient->medicine_id = intval($data['medicine_id']);
			$this->medicine_patient->patient_id = ($id) ? intval($data['patient_id']) : $this->id_patient;
			$this->medicine_patient->dosage = $data['dosage'];
			$this->medicine_patient->age_at_start = intval($data['age_at_start']);
			
					
			$this->medicine_patient->save();
			return $this->medicine_patient->id;
		}
	
		public function delete($id){
			$this->medicine_patient = ORM::factory("dao_medicinepatient",$id);
			$this->medicine_patient->delete();
			return $id;
		}
		
		public function getPatientMedicines($id=false){
			return ORM::factory("dao_medicinepatient")->where("patient_id","=",(!$id)?$this->id_patient:$id)->find_all()->as_array();
		}
		
	}
?>

